package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryType() {
        String key = CACHE_SHOP_TYPE_KEY;
        //1.查询所有的type
        List<String> shopTypeJson = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.判断这个缓存是否命中
        if (!CollectionUtil.isEmpty(shopTypeJson)){
            //命中,返回list给前端
            ArrayList<ShopType> shopTypes = new ArrayList<>();
            for (String str : shopTypeJson){
                shopTypes.add(JSONUtil.toBean(str,ShopType.class));
            }
            return Result.ok(shopTypes);
        }

        //不命中,查询数据库中所有的type
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        //不存在,返回401
        if (shopTypes == null || shopTypes.isEmpty()){
            return Result.fail("分类不存在");
        }

        //存在,写入缓存
        for (ShopType shopType : shopTypes){
            stringRedisTemplate.opsForList().leftPushAll(key,JSONUtil.toJsonStr(shopType));
        }

        return Result.ok(shopTypes);
    }
}
